package cn.likun.kit.database;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;

import javax.sql.DataSource;

import cn.likun.kit.validate.ValidateCommons;

/**
 *<p>数据库连接信息</p>
 *<p>数据库元信息工具类</p>
 */
public class MetaDataCommons {
	
	public static final String DB_TYPE_ORACLE = "oracle" ;
	public static final String DB_TYPE_DB2 = "db2";
	public static final String DB_TYPE_MYSQL = "mysql";
	public static final String DB_TYPE_SQLSERVER = "sqlserver";
	public static final String DB_TYPE_SYBASE = "sybase";
	
	private String driver;
	private String url;
	private String username;
	private String password;
	private DataSource dataSource;
	/**
	 * 构造方法
	 * @param driver 驱动
	 * @param url URL
	 * @param username 用户名
	 * @param password 密码
	 */
	public MetaDataCommons(String driver, String url, String username,
			String password) {
		this.driver = driver;
		this.url = url;
		this.username = username;
		this.password = password;
	}
	/**
	 * 基于DataSource 创建MetaDataCommons
	 * <p>警告: 使用DataSource (Oracle,Mysql)无法获取表备注</p>
	 * @param dataSource 数据源
	 */
	public MetaDataCommons(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	
	private Connection getConnection() throws SQLException, ClassNotFoundException{
		Connection conn = null;
		if (ValidateCommons.isNotEmpty(dataSource)) {
			conn = JdbcCommons.open(dataSource);
		} else if (ValidateCommons.isNotEmpty(driver) && ValidateCommons.isNotEmpty(url) && ValidateCommons.isNotEmpty(username) && ValidateCommons.isNotEmpty(password)) {
			conn = JdbcCommons.open(driver, url, username, password);
		}
		return conn;
	}
	
	private String toUpperCase(String value) {
		if (ValidateCommons.isNotEmpty(value)) { 
			value = value.toUpperCase();
		}
		return value;
	}
	/**
	 * 获取数据库类型
	 * @return 数据库类型 
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public DB_TYPE getDbType() throws ClassNotFoundException, SQLException {
		Connection conn = getConnection();
		try {
			DatabaseMetaData databaseMetaData = conn.getMetaData();
			return getDbType(databaseMetaData);
		} finally {
			JdbcCommons.close(conn, null, null);
		}
	}
	private DB_TYPE getDbType(DatabaseMetaData databaseMetaData) throws SQLException {
		String productName = databaseMetaData.getDatabaseProductName();
		productName = productName.toLowerCase();
		if (productName.indexOf("oracle") > -1) {
			return DB_TYPE.ORACLE;
		} else if (productName.indexOf("db2") > -1) {
			return DB_TYPE.DB2;
		}  else if (productName.indexOf("mysql") > -1) {
			return DB_TYPE.MYSQL;
		}  else if (productName.indexOf("sql server") > -1) {
			return DB_TYPE.SQLSERVER;
		}  else if (productName.indexOf("adaptive server") > -1) {
			return DB_TYPE.SYBASE;
		}
		return null;
	}
	
	
	
	
	
}























